#include "ZMap.h"

namespace Zdib
{
	CMap::CMap(CContainer *root,CContainer *parent,char *filename):CContainer(parent)
	{
		m_Img=NULL;
		SetRoot(root);
		m_Img=root->GetImgForPath(filename);
		m_BgImg=new CMapFile();
		m_BgImg->SetSize(ScreenW,ScreenH);
		W=m_Img->headInfo->biWidth;
		H=m_Img->headInfo->biHeight;
		MapX=0;
		MapY=0;
		OldMapX=0;
		OldMapY=0;
		LoadObstruct();
		m_BGDPosValue=CalDrawPosValue(m_Img->GetWidth(),m_Img->GetHeight(),MapX,MapY);
	}
	CMap::~CMap()
	{
		delete m_Obs;
		delete m_BgImg;
	}
	CImgFile *CMap::GetCurImg()
	{
		return (CImgFile *)m_BgImg;
	}

	void CMap::SetMapPos(int x,int y)
	{
		if(x>0)
			x=0;
		if(y>0)
			y=0;
		if(ScreenW-x>W)
			x=ScreenW-W;
		if(ScreenH-y>H)
			y=ScreenH-H;
		MapX=x;
		MapY=y;
		SetPos(x,y);
	}

	TPos CMap::GetMapPos()
	{
		TPos pos;
		pos.x=MapX;
		pos.y=MapY;
		return pos;
	}

	void CMap::Draw()
	{
		CImgFile *desimg;
		if(!m_Show)
			return;
		if(MapX!=OldMapX || MapY!=OldMapY)
		{
			m_BGDPosValue=CalDrawPosValue(m_Img->GetWidth(),m_Img->GetHeight(),MapX,MapY);
		}
		m_BgImg->Draw(m_Img,MapX,MapY,false,&m_BGDPosValue);
		OldMapX=MapX;
		OldMapY=MapY;
		CContainer::Draw();
		desimg=m_Parent->GetCurImg();
		if(desimg)
		{
			MoveMemory((char *)desimg->PixColors,(char *)m_BgImg->PixColors,desimg->headInfo->biSizeImage);
			//desimg->Draw(m_BgImg,0,0,false,&m_DPosValue);
		}
		
	}

	bool CMap::OnEvent(const TEvent& ev)
	{
		if(ev.event_type==ET_MouseEvent)
		{
			if(myEventReceiver!=NULL)
			{
				TEvent newev;
				newev=ev;
				newev.Mouse.Call=this;
				newev.Mouse.CallBack=NULL;
				return myEventReceiver->OnEvent(newev);
			}
			else
			{
				return m_Parent->OnEvent(ev);
			}
		}
		return false;
	}

	void CMap::LoadObstruct()
	{
		int tempw,temph,i,j;
		tempw=W/20;
		temph=H/20;
		m_Obs=new CObstruct();
		m_Obs->CreateObs(tempw,temph);
		m_Obs->SetWH(20,20);
		for(i=0;i<temph;i++)
		{
			for(j=0;j<tempw;j++)
			{
				if(m_Img->BmpData[i*20][j*20]->a==255)
				{
					m_Obs->SetGrids(i,j,j*20,i*20,false);
				}
				else
				{
					m_Obs->SetGrids(i,j,j*20,i*20,true);
				}
			}
		}
	}
}